package leeon.bbsbrower.views;

import ipworks.IPWorksException;
import leeon.bbsbrower.actions.BBSBoardAction;
import leeon.bbsbrower.models.BoardObject;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;

public class BoardDialog extends Dialog {
	
	
	private Combo all = null;
	
	/**
	 * Create the dialog
	 */
	public BoardDialog(Shell parentShell) {
		super(parentShell);		
	}
	
	/**
	 * Create contents of the dialog
	 * @param parent
	 */
	protected Control createDialogArea(Composite parent) {
		Composite container = (Composite) super.createDialogArea(parent);
		container.setLayout(new FillLayout());
		
		all = new Combo(container, SWT.BORDER|SWT.DROP_DOWN);
		all.setFont(ApplicationWorkbenchWindowAdvisor.listFont);
		
		
		try {
			BoardObject[] bs = BBSBoardAction.getAllBoards();
			if (bs != null) {
				for (int i = 0; i < bs.length; i ++) {
					all.add(bs[i].getCh());
				}
			}
		} catch (IPWorksException e) {
			MessageDialog.openError(this.getShell(), "错误信息", e.toString());
			e.printStackTrace();
		}
		
		
		
		all.addKeyListener(new KeyListener() {

			public void keyPressed(KeyEvent e) {
				//回车加入
				if (e.keyCode == 13) {
					actionAddBoard();
					e.doit = false;
				//回复	
				} else if (e.keyCode == SWT.ESC) {
					BoardDialog.this.close();
					e.doit = false;
				}
			}

			public void keyReleased(KeyEvent e) {}
			
		});
		all.setFocus();
		return container;
	}
	
	
    /**
     * 设定窗口的标题和图片
     */
    protected void configureShell(Shell shell) {
    	super.configureShell(shell);
    	shell.setText("选择版面");    	
    }
	
	/**
	 * 添加版面
	 *
	 */
	private void actionAddBoard() {
		if (all.getText() == null || all.getText().length() == 0) {
			this.close();
		}
		
		try {
			BoardObject[] bs = BBSBoardAction.getAllBoards();				
			for (int i = 0; i < bs.length; i ++) {
				if (all.getText().equals(bs[i].getCh()) || all.getText().equals(bs[i].getName())) {
					BBSBoardAction.addMyBoard(bs[i].getName(), bs[i].getCh().substring(bs[i].getCh().indexOf('(')+1, bs[i].getCh().length()-1));
					break;
				}
			}
			this.close();
		} catch (IPWorksException e) {
			MessageDialog.openError(this.getShell(), "错误信息", e.toString());
			e.printStackTrace();
		}
	}
		
	/**
	 * 去掉下面的button bar
	 */
	protected Control createButtonBar(Composite parent) {
		return null;
	}
	
	/**
	 * Return the initial size of the dialog
	 */
	protected Point getInitialSize() {
		return new Point(350, 60);
	}

}
